<template>
  <div>
    <!-- 公共的上传组件 -->
    <el-upload
      class="upload-demo"
      :drag="drag"
      :action="action"
      :show-file-list="showFileList"
      :list-type="listType"
      :headers="req_headers"
      :on-success="fileUpload_success"
      :on-error="fileUpload_error"
      :file-list="fileList"
      :multiple="multiple"
      :before-upload="beforeFileUpload"
      :data="data"
    >
      <div v-if="drag">
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </div>

      <div v-else>
        <el-button type="primary" size="small">{{ text }}</el-button>
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  props: {
    // 拖动上传
    drag: {
      type: Boolean,
      default: false,
    },

    // 服务器地址
    action: {
      type: String,
      default: () => {
        return "/api/api/saveFileData";
      },
    },

    // 是否显示文件列表
    showFileList: {
      type: Boolean,
      default: false,
    },

    // 是否支持多选
    multiple: {
      type: Boolean,
      default: false,
    },

    text: {
      type: String,
      default: "点击上传图片",
    },

    data: {
      type: Object,
      default: () => {
        return {};
      },
    },

    fileList: {
      type: Array,
      default: () => {
        return [];
      },
    },

    listType:{
      type: String,
      default: "text",
    }
  },

  computed: {
    // 计算属性，返回文件列表
    myFileList() {
      return this.fileList;
    },
  },

  data() {
    return {
      req_headers: {
        // "Accept-Charset": "UTF-8",
        token: JSON.parse(sessionStorage.getItem("userInfo")).token,
      },
    };
  },

  methods: {
    // 上传成功
    fileUpload_success(res, file) {
      if (this.multiple) {
        this.myFileList.push(file);
      } else {
        this.myFileList = [file];
      }
      this.$emit("success", {
        res: { ...res },
        file,
        fileList: this.myFileList,
      });
    },
    // 上传失败
    fileUpload_error() {
      this.$message.error("文件上传失败");
      this.$emit("error");
    },
    // 上传之前
    beforeFileUpload(file) {
      this.$emit("beforeFileUpload", file);
      // const allowedTypes = [
      //   "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      //   "application/vnd.ms-excel",
      //   "text/csv",
      // ];
      // const fileType = file.type;
      // if (!allowedTypes.includes(fileType)) {
      //   this.$message.error("只能上传 Excel 或 CSV 文件!");
      //   return false;
      // }
      // // 如果需要，你还可以在这里添加其他校验逻辑，比如文件大小等
      // return true; // 或者返回一个解析为 true 的 Promise
    },
  },
};
</script>

<style></style>
